package com.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.client.RecordCreateService;
import com.db.connection.DBCPPostgresManager;
import com.db.domain.Record;

/**
 * 根据本地的记录复制远程节点所需的记录 一个本地记录要被复制到所有其他节点
 * 
 * @author mike
 * 
 */
public class RecordCreateServiceClient implements Runnable {

	//线程运行的时间间隔，当遇到异常时时间间隔调大，并给以警告，正常时调小
	public static final int timeNormal  = 1000;
	public static final int timeERR  = 20000;	
	public static int dltTime = timeNormal;
	public static List<Long> list = new ArrayList<Long>();

	public static long insert(long id, Record record, Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet res = null;
		try {
			conn = DBCPPostgresManager.getConnection();
			// 执行SQL语句
			String sql = "insert into ad_record (id, content, operation, created, store_to, store_from, flag)values(?,?,?,?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setLong(1, getNextID() + 1);

			pstmt.setString(2, record.getContent());
			pstmt.setString(3, record.operation);
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			pstmt.setString(4, sft.format(new Date()));
			pstmt.setLong(5, record.storeId);
			pstmt.setLong(6, record.storeFrom);
			pstmt.setString(7, "N");
			pstmt.executeUpdate();
			pstmt.getConnection().commit();

		}  finally {
			DBCPPostgresManager.close(conn, pstmt, rs);

		}
		return 0;
	}

	private static long getNextID() throws SQLException {
		long id = 0;
		Connection conn = null;
		// 加载Connector/J驱动
		try {
			conn = DBCPPostgresManager.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 执行SQL语句
		String sql = "select max(id) from ad_record";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				id = rs.getLong(1);
			}
		} catch (Exception e) {
			System.out.print(e);
		} finally {
			DBCPPostgresManager.close(conn, pstmt, rs);
		}
		return id;

	} // fillCombos

	/**
	 * 从中央服务器取得需要同步的记录
	 * 
	 * @return
	 */
	public static long receiveRecord() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		SyncService aSyncService = null;
		List<Record> list = null;		
		try {
			conn = DBCPPostgresManager.getConnection();
			aSyncService = SyncServiceFactory.getSyncService();
			// 事务开始，去服务端取数据，还需要设置标志
			list = aSyncService.serverToClient(RecordCreateService.orgid);
			if (list == null) {
				System.out.println("Error : " + 1);
			}
			List<Long> list2 = new ArrayList<Long>();
			for (Record aRecord : list) {
				list2.add(aRecord.getId());
				insert(aRecord.getStoreId(), aRecord, conn);
			}
			aSyncService.setFlag(list2);
			// 事务结束
			conn.commit();
			dltTime = timeNormal;
			if(list.size()>0) {
				//System.out.println("receiveRecord:"+list.size());
			}
			
		} catch (Exception ex) {
			if(conn!=null) {
				try {
					conn.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			dltTime = timeERR;
			//警报
			//TODO
			System.out.println("Error : " + ex.toString());
		} finally {
			DBCPPostgresManager.close(conn, pstmt, null);
		}
		return 0;
	}

	public Record getRecord() {
		Record aRecord = null;

		return aRecord;
	}

	/**
	 * @param args
	 */
	public static void main(String args[]) {

	}

	public void run() {
		try {
			while (true) {
				receiveRecord();
				Thread.currentThread().sleep(dltTime);
				//System.out.println("next...");
			}
		} catch (InterruptedException e) {			
			e.printStackTrace();
		}

	}
}
